package 多线程和队列.锁;

/**
 * java5 之前锁实现
 * @author 孔令富  2021/12/20
 */
class ShareDataOne{
    private int number = 0 ;
    public synchronized void increment() throws InterruptedException {
        while (number !=0){
            this.wait();
        }
       ++number;
        System.out.println(Thread.currentThread().getName() + "\t"+ number);
        this.notifyAll();

    }

    public synchronized  void decrement() throws InterruptedException {
        while (number == 0){
            this.wait();
        }

        --number;
        System.out.println(Thread.currentThread().getName()+"\t" + number);

        this.notifyAll();
    }
}

public class SychronizedDemo {

    public static void main(String[] args) {
        ShareDataOne shareDataOne = new ShareDataOne();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    shareDataOne.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    shareDataOne.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }

}
